#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time
import datetime
import json
import random
from generate.generator import BasicGenerator

import logging


class SycmWordGenerator(BasicGenerator):
    def get_keywords(self):
        sql = '''select keyword from sycm_keyword 
                where category_1 like '%美容美体%'
                or category_1 like '%个人护理%'
                or category_1 like '%生活电器%'
                or category_1 like '%厨房电器%';
            '''
        rows = self.mdb.query(sql)
        words = []
        for row in rows:
            words.append(row[0])
        return words

    def gen_task(self, extra=None):
        cur_time = datetime.datetime.now()
        pre_time = cur_time + datetime.timedelta(days=-1)
        pre_day = pre_time.strftime('%Y-%m-%d')
        snatch_day = int(pre_time.strftime('%Y%m%d'))
        url = 'https://sycm.taobao.com/mc/searchword/relatedWord.json'
        key_words = self.get_keywords()
        i = random.randint(0, len(key_words))
        words = [key_words[i]]
        words = key_words
        for word in words:
            task = {
                'type': self.name,
                'url': url,
                'params': {
                    'dateRange': '{0}|{1}'.format(pre_day, pre_day),
                    'dateType': 'day',
                    'pageSize': 10,
                    'page': 1,
                    'order': 'desc',
                    'orderBy': 'seIpvUvHits',
                    'keyword': word,
                    'device': 0,
                    'indexCode': 'seIpvUvHits,sePvIndex,clickRate,clickHits,clickHot',
                    '_': int(round(time.time() * 1000)),
                },
                'snatch_day': snatch_day
            }
            length = self.rds.rpush(self.queue_name, json.dumps(task))
            logging.info('{0} {1}'.format(length, task))
            self.stat.incr(self.stat_hash, 'gen_task')
